package models

import (
	"time"
	"github.com/astaxie/beego/orm"
	"strconv"
	"read.com/admin/libs"
	"encoding/base64"
)

type RecComment struct {
	Id         int       `orm:"column(id);auto"`
	UserId     string    `orm:"column(user_id);size(8)" description:"用户ID"`
	BookId     int       `orm:"column(book_id)" description:"书ID"`
	Message    string    `orm:"column(message);size(255)" description:"评论内容"`
	StarScore  int8      `orm:"column(star_score)" description:"星级评分"`
	CreateDate time.Time `orm:"column(create_date);type(datetime)" description:"反馈日期"`
	IsConfirm  int8      `orm:"column(is_confirm)" description:"是否已经确认"`
	UpdateDate time.Time `orm:"column(update_date);type(datetime);null" description:"审核时间"`
}

type FormatRecComment struct {
	Id         int
	Sort       int
	UserId     string
	BookId     int
	Name       string
	Message    string
	StarScore  int8
	CreateDate time.Time
	IsConfirm  int8
	UpdateDate time.Time
}

type BookRating struct {
	BookId      int
	Cnt         int
	BookName    string
	ChannelType int8
	Category    int
	Cat         string
	Status      int8
	StatusText  string
}



func (t *RecComment) TableName() string {
	return "rec_comment"
}

func init() {
	orm.RegisterModel(new(RecComment))
}

func GetRecCommentList(isConfirm int8, name string, page int, pageSize int) ([]*FormatRecComment, int) {
	o := orm.NewOrm()
	offset := (page - 1) * pageSize
	formatRecComment := make([]*FormatRecComment, 0)
	total := 0
	if isConfirm == -1 {
		sqlStr := "SELECT b.name,rc.* FROM book b,rec_comment rc WHERE b.id = rc.book_id AND b.`name` LIKE '%" + name + "%' order by create_date desc limit " + strconv.Itoa(offset) + "," + strconv.Itoa(pageSize)
		o.Raw(sqlStr).QueryRows(&formatRecComment)

		sqlCount := "SELECT count(*) FROM book b,rec_comment rc WHERE b.id = rc.book_id AND b.`name` LIKE '%" + name + "%'"
		o.Raw(sqlCount).QueryRow(&total)
	} else {
		sqlStr := "SELECT b.name,rc.* FROM book b,rec_comment rc WHERE b.id = rc.book_id AND rc.is_confirm = ? AND b.`name` LIKE '%" + name + "%' order by create_date desc limit " + strconv.Itoa(offset) + "," + strconv.Itoa(pageSize)
		o.Raw(sqlStr, isConfirm).QueryRows(&formatRecComment)

		sqlCount := "SELECT count(*) FROM book b,rec_comment rc WHERE b.id = rc.book_id AND rc.is_confirm = ? AND b.`name` LIKE '%" + name + "%'"
		o.Raw(sqlCount, isConfirm).QueryRow(&total)
	}

	sort := 1
	for _, v := range formatRecComment {
		v.Sort = sort
		sort ++
	}
	return formatRecComment, total
}

func UpdateIsConfirmById(id int) error {
	o := orm.NewOrm()
	_, err := o.Raw("update rec_comment set is_confirm = ? , update_date = ? where id = ? ", 1, time.Now(), id).Exec()
	if err != nil {
		return err
	}
	return nil
}

func DelById(id int) error {
	o := orm.NewOrm()
	if _, err := o.Delete(&RecComment{Id: id}); err == nil {
		return nil
	} else {
		return err
	}
}

func GetAllBookRating(name string, page int, pageSize int) ([]*BookRating, int64) {
	o := orm.NewOrm()
	offset := (page - 1) * pageSize
	bookRatings := make([]*BookRating, 0)
	total := 0
	sqlStr := "SELECT a.book_id as book_id, COUNT(a.user_id) as cnt, b.name as book_name,b.channel_type,b.category,b.status " +
		"FROM rec_comment a INNER JOIN book b ON(a.book_id = b.id) " +
		"WHERE b.name like '%" + name + "%' GROUP BY a.book_id limit " + strconv.Itoa(offset) + "," + strconv.Itoa(pageSize)
	o.Raw(sqlStr).QueryRows(&bookRatings)

	for _, v := range bookRatings {
		book := GetBookByID(v.BookId)
		// 判断书籍是否上架连载完结
		if compare := libs.CompareTime(book.ReleaseTime, time.Now()); compare >= 0 {
			v.StatusText = "未上架"
		} else {
			if v.Status == 0 {
				v.StatusText = "更新中"
			} else {
				if book.ReleaseChapterTotal() == book.ChapterTotal {
					v.StatusText = "已完结"
				} else {
					v.StatusText = "更新中"
				}
			}
		}
		for _, cat := range catList {
			if v.Category == cat.Id {
				v.Cat = cat.CategoryFullname
				break
			}
		}
	}

	sqlCount := "SELECT count(*) from" +
		"(SELECT a.book_id as book_id, COUNT(a.user_id) as cnt, b.name as book_name " +
		"FROM rec_comment a INNER JOIN book b ON(a.book_id = b.id) GROUP BY a.book_id) a"
	o.Raw(sqlCount).QueryRow(&total)

	return bookRatings, int64(total)
}


type UserRating struct {
	UserId     string
	Nickname   string
	BookId     int
	Name   string
	Message    string
	StarScore  int8
	CreateDate time.Time
	UpdateDate time.Time
	IsConfirm  int8
}


func GetUserRatingList(page int, pageSize int) ([]map[string]string, int64,map[int]map[string]string) {
	o := orm.NewOrm()
	offset := (page - 1) * pageSize
	userRatings := make([]*UserRating,0)
	count := 0
	sqlStr := "select u.user_id, u.nickname,r.book_id,b.name,r.message,r.star_score,r.create_date,r.update_date,r.is_confirm from user u,rec_comment r,book b where u.user_id = r.user_id and r.book_id = b.id order by r.create_date desc limit " + strconv.Itoa(offset) + "," + strconv.Itoa(pageSize)
	o.Raw(sqlStr).QueryRows(&userRatings)
	sqlCount := "select count(*) from user u,rec_comment r,book b where u.user_id = r.user_id and r.book_id = b.id"
	o.Raw(sqlCount).QueryRow(&count)
	results := make([]map[string]string,0)
	for k,v := range userRatings{
		nickname,_ := base64.StdEncoding.DecodeString(v.Nickname)
		result := map[string]string{
			"sort":strconv.Itoa(k+1),
			"userId":v.UserId,
			"nickname":string(nickname),
			"bookId":strconv.Itoa(v.BookId),
			"bookName":v.Name,
			"score":strconv.Itoa(int(v.StarScore)),
			"message":v.Message,
			"createDate":v.CreateDate.Format("2006-01-02 15:04:05"),
			"updateDate":v.UpdateDate.Format("2006-01-02 15:04:05"),
			"isConfirm":strconv.Itoa(int(v.IsConfirm)),
		}
		results = append(results, result)
	}
	tableHead := map[int]map[string]string{
		0:{"sort":"序号"},
		1:{"userId":"用户Id"},
		2:{"nickname":"用户名"},
		3:{"bookId":"小说Id"},
		4:{"bookName":"小说名称"},
		5:{"score":"星级评分"},
		6:{"message":"评论内容"},
		7:{"createDate":"评论时间"},
		8:{"updateDate":"审核时间"},
		9:{"isConfirm":"状态"},
	}
	return results, int64(count),tableHead
}
